<style lang="scss" scoped>
  @import '../../styles/common/loading.less';
  .container{
    border: none !important;
    margin-top: 4px;
  }
  .el-col-offset-1 {
    margin-left: 0%;
  }
  .button_a {
    background-color: rgba(255, 138, 0, 1);
    border-color: rgba(255, 138, 0, 1);

  }
  .col_a {
    margin-left: 2%;
  }
  .el-card {
    height: 200px;
  }

  .el-button--primary {
    background-color: rgba(255, 138, 0, 1);
    border-color: rgba(255, 138, 0, 1);
  }
</style>
<template>
    <div>
        <div class="container">
            <!-- 查询条件 -->
            <el-form :model="formInline" class="select-submit-form">
                <el-row type="flex">
                    <el-col :span="8" >
                        <el-form-item label="归属名称">
                            <!-- <el-select v-model="formInline.comCode" @change="changeComCode" placeholder="请选择归属机构">
                                <el-option v-for="item in comList" :key="item.comCode" :label="item.comName" :value="item.comCode"> </el-option>
                            </el-select> -->
                             <el-autocomplete
                              popper-class="my-autocomplete"
                              v-model="formInline.comName"
                              :fetch-suggestions="querySearchCom"
                              placeholder="点击查询归属机构"
                              class="class_b"
                              @select="handleSelectCom">
                              >
                              <template slot-scope="{ item }">
                                <div>{{ item.value }}-{{ item.comCode}}</div>
                              </template>
                            </el-autocomplete> 
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="医疗机构名称">
                            <!-- <el-select  v-model="formInline.hospitalCode" placeholder=""  @change="changeHospitalCode">
                                <el-option v-for="item in hospitalList" :key="item.hospitalCode" :label="item.hospitalName" :value="item.hospitalCode"> </el-option>
                            </el-select> -->
                            <!-- <el-autocomplete
                              popper-class="my-autocomplete"
                              v-model="formInline.hospitalName"
                              :fetch-suggestions="querySearch"
                              placeholder="点击查询"
                              class="class_b"
                              @select="handleSelect">
                              >
                              <template slot-scope="{ item }">
                                <div>{{ item.value }}-{{ item.hospCode}}</div>
                              </template>
                            </el-autocomplete> -->
                            <!-- <el-input v-model="formInline.hospitalCode" @click="hospitalDialogVisible = true" ></el-input> -->
                            <el-input  style="margin-top: 5px" v-model="formInline.hospitalName" placeholder="" disabled>
                                <el-button slot="append" @click="hospitalDialogVisible = true" icon="el-icon-search"></el-button>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="是否重开">
                            <el-select v-model="formInline.taskType"  @change="changeIsReopen">
                                <el-option label="否" value="0"></el-option>
                                <el-option label="是" value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col> 
                </el-row>
                <el-row type="flex">
                    <el-col :span="8">
                        <el-form-item label="开始日期">
                            <el-date-picker
                                v-model="formInline.startDate"
                                type="date"
                                placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" >
                        <el-form-item label="终止日期">
                            <el-date-picker
                                v-model="formInline.endDate"
                                type="date"
                                placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="批次号">
                            <el-input v-model="formInline.batchNo" ></el-input>
                        </el-form-item>
                    </el-col> 
                </el-row>
                <el-row type="flex" v-if='isShow'>
                    <el-col :span="8">
                        <el-form-item label="结算单号">
                            <el-input v-model="formInline.settleNo" ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>    
                <el-row>
                  <el-col :span="24">
                    <div class="select-btn-group">
                      <el-button type="primary" size="medium"  @click="handleSearch">查询</el-button>
                      <el-button type="primary" size="medium" @click="handleReset">重置</el-button>
                      <el-button type="primary" size="medium" @click="applyCost" >申请结算</el-button>
                    </div>
                  </el-col>
                </el-row>
            </el-form>
            <!-- <template>
                <div>
                <el-divider></el-divider>
                </div>
            </template>  -->
            <!-- 列表 -->
            <el-table
                :data="tableData"
                class="table"
                row-key="caseNo"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
                style="margin: 30px 0;border: 1px solid #d6d9d8;"
                v-loading="loading"
                element-loading-text="Loading....."
            >
                <el-table-column fixed type="selection"  width="55" :reserve-selection='true'></el-table-column>
                <el-table-column prop="caseNo" label="大病赔案号"  width="165" align="center">
                    <template  slot-scope="scope">
                        <a href="#">{{scope.row.caseNo}}</a>
                    </template>
                </el-table-column>
                <el-table-column prop="medicalType" label="医疗类别" align="center"></el-table-column>
                <el-table-column prop="sumAmount" label="医疗费用金额" align="center"></el-table-column>
                <el-table-column prop="sumPayAmount" label="实际支付金额" align="center"></el-table-column>
                <el-table-column prop="undwrtDate" label="核赔日期"  width="150" align="center"></el-table-column>
            </el-table>
            <div class="pagination">
            <div v-show=" pagination.totalPage>0" class="index_page">
              <el-pagination :current-page="pagination.currentPage" :page-size="pagination.rowsNumber"
                             :page-sizes="[10, 25, 50, 100, 500, 1000, 5000]"
                             :total="pagination.totalPage" background layout="prev, pager, next,sizes,total,jumper"
                             @size-change="handleSizeChange" @current-change="queryFun">
              </el-pagination>
            </div>
            </div>

            <!-- 医疗机构选择弹框 -->
            <el-dialog
                title="医疗机构信息"
                :visible.sync="hospitalDialogVisible"
                width="60%"
                center>
                <template>
                    <div class="container">
                        <el-form :model="prpLHospCompany" ref="prpLHospCompany">
                            <el-row type="flex">
                                <el-col :span="12">
                                    <el-form-item label="医疗机构名称" prop="hospName">
                                        <el-input placeholder="" v-model="prpLHospCompany.hospName"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="医疗机构编码" prop="hospCode">
                                        <el-input placeholder=""  v-model="prpLHospCompany.hospCode"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                            <el-col :span="24">
                                <div class="select-btn-group">
                                    <el-button type="primary" size="medium"  @click="queryHospList">查询</el-button>
                                    <el-button type="primary" size="medium" @click="resetForm('prplPayeeList')">重置</el-button>
                                </div>
                            </el-col>
                            </el-row>
                        </el-form>
                        <el-table
                        :data="hospitalList"
                        class="table"
                        ref="multipleTable"
                        header-cell-class-name="table-header"
                        style="margin-top: 10px"
                        >
                            <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
                            <el-table-column prop="hospName" label="医疗机构名称" align="center">
                                <template  slot-scope="scope">
                                    <a href="#" style="color: #409EFF" @click="choseHosp(scope.row)">{{scope.row.hospName}}</a>
                                </template> 
                            </el-table-column>
                            <el-table-column prop="hospCode" label="医疗机构编码" align="center">
                                <template  slot-scope="scope">
                                    <a href="#" style="color: #409EFF" @click="choseHosp(scope.row)">{{scope.row.hospCode}}</a>
                                </template>     
                            </el-table-column>
                        </el-table>
                        <div class="pagination">
                            <el-pagination :current-page="hosppagination.currentPage" :page-size="hosppagination.rowsNumber"
                                            :total="hosppagination.totalPage" background layout="prev, pager, next,total,jumper"
                                            @current-change="hospQueryFun">
                            </el-pagination>
                        </div>
                    </div>
                </template>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="hospitalDialogVisible = false">关闭</el-button>
                </div>
            </el-dialog>
            <!-- 结算信息 -->
            <el-dialog
                    title="结算信息"
                    :visible.sync="costInfo"
                    width="35%"
                    center>
                <div>
                    <div>
                        <el-table
                            :data="costData"
                            border
                            class="table"
                            ref="multipleTable"
                            header-cell-class-name="table-header"
                            style="margin-top: 10px"
                        >
                            <el-table-column prop="hospName" width="200" label="结算机构" align="center"   show-overflow-tooltip></el-table-column>
                            <el-table-column prop="settleNum" label="结算案件总数" align="center" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="actualPaymentAmount" label="结算总金额" align="center"  show-overflow-tooltip></el-table-column>
                        </el-table>
                    </div>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="costInfo = false">取  消</el-button>
                    <el-button type="primary" @click="toSettlement" >确  认</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import{querySettleCaseInfo, queryHospCompanyList, queryAllLowerCompanysList, applySettlement}from '@/api/baseDate';
import moment, { relativeTimeRounding } from 'moment';
import Cookies from "js-cookie";
export default {
    name: 'settlementTask',
    data() {
        return {
            loading: false,
            isShow: false,
            pagination: {
                currentPage: 1, // 当前页
                rowsNumber: 10, // 每页条数
                totalPage: 0 // 总条数
            },
            comList:[], // 归属机构
            comCode:'', // 归属机构编码
            comName:'', // 归属机构名称
            hospitalDialogVisible: false,
            prpLHospCompany: {}, // 医疗机构对象
            hospitalList:[], // 医疗机构列表
            hosppagination:{
                currentPage: 1, // 当前页
                rowsNumber: 5, // 每页条数
                totalPage: 0 // 总条数
            },
            hospitalCode:'', // 医疗机构编码
            hospitalName:'', // 医疗机构名称
            restaurants:[],
            multipleSelection: [], // 全选集合
            delList: [],
            costInfo:false, // 结算弹框
            formInline: { // 查询条件
                comName:'',
                comCode: '',
                hospitalName: '',
                hospitalCode: '',
                taskType: '0', // 默认正常案件
                startDate: '',
                endDate: '',
                settleNo: '', 
                batchNo: '',
            },
            tableData:[], // 查询的列表数据
            costData:[],  // 申请结算弹框列表数据
            data:{}, // 封装结算数据
            prpLSettlementDTO: {},
            resultData: {}
        };
    },
    created() {
        // 加载归属机构
        this.queryComList();
        // 加载医保机构
        // this.hospCompanyList();
    },
    methods: {
        // 归属机构
        queryComList(){
            var param = {
                comCode: Cookies.get("makeCom")
            } 
            queryAllLowerCompanysList(param).then(res => {
                this.comList=res.data.map(item=>{
                    return {
                            'comCode': item.comCode,
                            'value': item.comCName
                        }
                    })
            })
        },
        createFilter(queryString) {
            return (restaurant) => {
            return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        querySearchCom(queryString, cb){
            var restaurants = this.comList;
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
            // 调用 callback 返回建议列表的数据
            if (results.length === 0) {
                this.formInline.comName=null;
                cb(restaurants);
            } else {
                cb(results);
            }
        },
        handleSelectCom(item){
            this.formInline.comCode=item.comCode;
        },
        // 查询医疗机构
        queryHospList(){
            let param = {
                ...this.prpLHospCompany,
                pageNum: this.hosppagination.currentPage,
                pageSize: this.hosppagination.rowsNumber
            }
            queryHospCompanyList(param)
                .then(res => {
                    this.hospitalList = res.data.list;
                    this.hosppagination.totalPage = res.data.total;
                })
        },
        //医疗机构查询 （暂未使用）
        hospCompanyList(){
            queryHospCompanyList({pageNum:1, pageSize:100000}
            ).then(res => {
                this.restaurants=res.data.list.map(item=>{
                    return {
                            hospCode:item.hospCode,
                            value:item.hospName
                        }
                    })
            })
        },
        handleSelect(item){
            this.formInline.hospitalCode=item.hospCode;
        },
        querySearch(queryString, cb) {
            var restaurants = this.restaurants;
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
            // 调用 callback 返回建议列表的数据
            if (results.length === 0) {
                this.formInline.hospitalName=null;
                cb(restaurants);
            } else {
                cb(results);
            }
        },
        // 改变当前页条数事件
        handleSizeChange(pageSize){
            this.pagination.rowsNumber=pageSize
            this.queryTaskList();
        },
        // 改变当前页事件
        queryFun(pageNum){ 
            this.pagination.currentPage = pageNum;
            this.queryTaskList();
        },
        // 监听是否重开事件
        changeIsReopen(){
            let isReopen =  this.formInline.taskType;
            if(isReopen === '1'){
                this.isShow = true;
            }else{
                this.isShow = false;
                this.formInline.settleNo = '';
            }
        },
        // 改变医疗机构
        hospQueryFun(pageNum){ 
            this.hosppagination.currentPage = pageNum;
            this.queryHospList();
        },
        // 选择医疗机构
        choseHosp(row){
            this.hospitalCode = row.hospCode;
            this.hospitalName = row.hospName;
            this.formInline.hospitalCode = row.hospCode;
            this.formInline.hospitalName = row.hospName;
            this.hospitalDialogVisible = false;
        },
        // 归属机构变更事件 （暂未使用）
        changeComCode(val){  
            this.comList.map((item)=>{
                if(item.comCode === val){
                    this.comCode = item.comCode;
                    this.comName = item.comName;
                }
            })
            // 清空查询条件
            this.formInline.startDate = '';
            this.formInline.endDate = '';
        },
        // 医保机构变更事件（暂未使用）
        changeHospitalCode(val){
            this.hospitalList.map((item)=>{
                if(item.hospitalCode === val){
                    this.hospitalCode = item.hospitalCode;
                    this.hospitalName = item.hospitalName;
                }
            })
        },
        // 查询满足条件结算案件列表
        queryTaskList(){
            let param = {
                ...this.formInline,
                pageNum: this.pagination.currentPage,
                pageSize: this.pagination.rowsNumber,
            }
            if (this.isEmptyStr(param.batchNo)){
                // 校验归属机构
                if(this.isEmptyStr(param.comCode)){
                    this.$message.warning(`请选择归属名称！`);
                    return;
                }
                    // 校验医保机构 
                if(this.isEmptyStr(param.hospitalCode)){
                    this.$message.warning(`请选择医疗机构！`);
                    return;
                }
            }

            if(param.taskType === '1' && (param.settleNo == undefined ||  param.settleNo == null ||  param.settleNo == '')){
                this.$message.warning(`结算重开案件需输入结算单号！`);
                return;
            }

            // 转换时间格式
            param.startDate = param.startDate ? moment(param.startDate).format('YYYY-MM-DD HH:mm:ss') : '';
            param.endDate = param.endDate ? moment(param.endDate).format('YYYY-MM-DD HH:mm:ss') : '';
            // 禁止重复点击
            if(this.loading){
                return;
            }
            // 调用查询方法
            this.loading = true;
            querySettleCaseInfo(param).then((res)=> this.handleTaskListResponse(res));
        },
        // 处理查询结算案件列表返回数据
        handleTaskListResponse(res){ 
            this.loading = false;
            if(res){
                if(res.data.resultCode){
                    if(res.data.resultCode != '0000'){ 
                        // 返回失败
                        this.$message.error(res.data.resultMsg);
                    }else{
                        // 返回成功
                        this.tableData = res.data.list;
                        this.pagination.totalPage = res.data.total;
                    }
                }
            }else{
                this.$message.error('系统异常'); 
            }
        },
        // 申请结算弹框
        applyCost(){ 
            let settleNum =  this.multipleSelection.length;
            if(settleNum == 0){
                this.$message.warning("请选择需要结算的案件！");
                return;
            }
            let  costTotal = 0;
            this.multipleSelection.forEach((item) => {
                costTotal += item.sumPayAmount
                this.comCode = item.comCode;
                this.comName = item.comName;
                this.hospitalCode = item.hospitalCode;
                this.hospitalName = item.hospitalName;
            });
            this.costTotal = costTotal;
            this.costData = [
                {
                    hospName:this.hospitalName,
                    settleNum:settleNum,
                    actualPaymentAmount:costTotal
                }
            ]
            this.costInfo = true;
        },
        // 跳转结算任务明细页面
        toSettlement(){ 
            let settleNum = this.multipleSelection.length; // 结算笔数        
            let medicalFeeAmount = 0.0;  // 医疗费用金额 
            let deductionAmount = 0.0;  // 扣款金额    
            let supplementAmount = 0.0;  // 应补金额   
            let actualPaymentAmount = 0.0;  // 实际支付金额
            let settleCaseInfoList = [];
            this.multipleSelection.forEach((item) => {
                medicalFeeAmount += item.sumAmount;
                actualPaymentAmount += item.sumPayAmount;
                settleCaseInfoList.push(item);
            });
            this.prpLSettlementDTO = {
                comCode: this.comCode,
                comName: this.comName,
                hospName: this.hospitalName,
                hospCode: this.hospitalCode,
                isReopen: this.formInline.taskType,
                settleNum: settleNum,
                medicalFeeAmount: medicalFeeAmount,
                deductionAmount: deductionAmount,
                supplementAmount: supplementAmount,
                actualPaymentAmount: actualPaymentAmount,
                settleCaseInfoList: settleCaseInfoList
            }
            this.data = this.prpLSettlementDTO;
            // applySettlement(this.data)
            //             .then(res => {
            //                 if(res){
            //                     if(res.data.resultCode){
            //                         if(res.data.resultCode != '0000'){ 
            //                             // 返回失败
            //                             this.$message.error(res.data.resultMsg);
            //                             return;
            //                         }else{
            //                             // 返回成功
            //                             this.$message.success(res.data.resultMsg);
            //                             this.resultData = {
            //                                taskId: res.data.taskId,
            //                                settleNo: res.data.settleNo
            //                             }

            //                         }
            //                     }else{
            //                         this.$message.error('系统异常'); 
            //                         return;
            //                     }
            //                 }else{
            //                     this.$message.error('系统异常'); 
            //                     return;
            //                 }

            //             });
            this.$router.push({
                name: 'settlementTaskDetail',
                params: this.data,
            });
            // 关闭申请结算弹框
            this.costInfo=!this.costInfo;

        },
        // 查询
        handleSearch() {
            this.queryTaskList();
        },
        // 重置
        handleReset(){

        },
        handleSelectionChange(val) { // 多选操作
            this.multipleSelection = val;
        },          
        handleDelete(index, row) { // 删除操作
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.$message.success('删除成功');
                    this.tableData.splice(index, 1);
                })
                .catch(() => {});
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        }
    }

};
</script>
